<template>
    <view class="w-full mt-2 bg-white rounded-lg p-2 box-border text-[9px] color-[#999] flex flex-col gap-2">
        <DateView />
        <!-- 项目规格 -->
        <view class="flex align-center items-center" v-if="feeControl.spec">
            <text class="">项目规格：</text>
             <view class="flex flex-wrap gap-2 items-center">
                <nut-button size="small" :type="sku.cur.id === item.id ? 'success' : 'default'" @click="sku.cur = item" v-for="item in sku.options" :key="item.id">
                    {{item.type}}
                </nut-button>
            </view>
            <text class="ml-auto text-red-500">¥{{ sku.cur?.price || 0 }}元</text>
        </view>

        <!-- 技术层级 -->
        <view class="flex align-center items-center" v-if="feeControl.expert">
            <text class="">技术层级：</text>
            <view class="flex items-center" @tap="popTechPicker">
                <text class="text-blue-500">{{ expert.cur?.name || '选择' }}</text>
            </view>
            <text class="ml-auto text-red-500">¥{{ expert.cur?.fee || 0 }}元</text>
        </view>

        <!-- 预约上门地址 -->
        <view class="flex items-center">
            <text class="">预约上门地址：</text>
            <view class="flex items-center cursor-pointer" @tap="openMap">
                <text class="mr-2">{{ address || '点击选择地址' }}</text>
                <text class="text-green-500 text-lg">📍</text>
                <text class="ml-2" v-if="distance">{{ distance }}km</text>
            </view>
        </view>
        <!-- 远程费信息 -->
        <view class="flex flex-col gap-2" v-if="feeControl.distance">
            <view class="flex" v-for="item in records" :key="item.name">
                <text class="mr-2">{{ item.name }}：</text>
                <text class="">¥{{ item.fee }}</text>
            </view>
            <view class="flex">
                <text></text>
                <view class="flex justify-between ml-auto">
                    <text class="">远程费小计：</text>
                    <text class="text-red-500">¥{{ distanceFee }}</text>
                </view>
            </view>

        </view>

        <!-- <view class="flex align-center items-center">
            <text class="">超时：</text>
            <text class="ml-auto text-red-500">¥{{ overtimeFee }}元</text>
        </view>


        <view class="flex">
            <text class="whitespace-nowrap">超时（小时/天）：</text>
            <text class="flex-1">每超过1小时需加收（不足1小时按1小时算）(5公里内远程费+技术服务费</text>
        </view> -->


        <!-- 根据时间段显示额外收费项目 -->
        <view v-if="startDate" class="flex flex-col gap-2 bg-orange-50 p-2 rounded">
            <text class="font-bold text-orange-600">时间段额外收费：</text>
            <view class="flex justify-between" v-if="getCurrentHurryFee() > 0">
                <text class="text-sm">加急费：</text>
                <text class="text-red-500 font-bold">¥{{ getCurrentHurryFee() }}</text>
            </view>
            <view class="flex justify-between" v-if="isMoon === '1'">
                <text class="text-sm">夜班费：</text>
                <text class="text-red-500 font-bold">¥1000</text>
            </view>
            <view class="flex justify-between" v-if="isWeek === '1'">
                <text class="text-sm">节假日费：</text>
                <text class="text-red-500 font-bold">¥500</text>
            </view>
            <view class="flex justify-between border-t pt-2 mt-2">
                <text class="font-bold">时间段费用小计：</text>
                <text class="text-red-500 font-bold">¥{{ getTotalTimeFee() }}</text>
            </view>
        </view>

        <!-- 接送 -->
        <view class="flex align-center items-center">
            <text class="block font-bold">接送：</text>
            <view class="flex items-center">
                <nut-radio-group v-model="pickup.choose" direction="horizontal">
                    <nut-radio :label="false" size="small">否</nut-radio>
                    <nut-radio :label="true" size="small">是</nut-radio>
                </nut-radio-group>
            </view>
            <!-- <text class="ml-auto">价格：{{ isPick == 1 ? totalWay : 0 }}元</text> -->
            <text class="ml-auto text-red-500">¥{{ pickupFree }}元</text>
        </view>

        <!-- 备注 -->
        <view class="flex align-center items-center">
            <text class="block font-bold">备注：</text>
            <view class="flex items-center flex-1">
                <nut-input class="iptx" v-model="goodsStore.remark" />
            </view>
        </view>

      

        <nut-popup v-model:visible="showTimePicker" position="bottom">
            <nut-date-picker type="datetime" v-model="val" :min-date="min" :max-date="max" :three-dimensional="false"
                @confirm="confirmTime" @cancel="showTimePicker=false"></nut-date-picker>
        </nut-popup>

        <nut-popup v-model:visible="showTechPicker" position="bottom">
            <nut-picker v-model="techPickerValue" :columns="expert.options" :field-names="pickFieldNames" title="选择技术层级"
                @confirm="confirmTechLevel"  @cancel="showTechPicker=false"/>
        </nut-popup>

        <nut-popup v-model:visible="showSpePicker" position="bottom">
            <nut-picker v-model="spePickerValue" :columns="speLevelOptions" title="选择规格"
                @confirm="confirmSpeLevel"  @cancel="showSpePicker=false"/>
        </nut-popup>

        <nut-popup v-model:visible="showHurry" position="bottom">
            <nut-picker v-model="hurryValue" :columns="urgent.options" :field-names="pickFieldNames" title="选择加急"
                @confirm="confirmHurry" @cancel="showHurry=false"/>
        </nut-popup>

        <!-- 时间段费用提示弹窗 -->
        <nut-popup v-model:visible="showTimeAlert" position="center" :style="{ width: '80%' }">
            <view class="p-4">
                <view class="text-center mb-4 font-bold text-lg">费用提示</view>
                <view class="mb-4">
                    <view v-if="timeAlertInfo.hurryFee > 0" class="mb-2">
                        根据您选择的时间段，需要加收加急费 <text class="text-red-500">¥{{ timeAlertInfo.hurryFee }}</text>
                    </view>
                    <view v-if="timeAlertInfo.isNightShift" class="mb-2">
                        检测到您选择的时间段包含夜班时间(18:00 - 次日9:00)，需要加收夜班费 <text class="text-red-500">¥1000</text>
                    </view>
                    <view v-if="timeAlertInfo.isWeekend" class="mb-2">
                        检测到您选择的时间段包含周末，需要加收节假日费 <text class="text-red-500">¥500</text>
                    </view>
                </view>
                <view class="flex justify-center gap-8">
                    <nut-button type="default" class="w-[200rpx]" size="small" @tap="cancelTimeSelection">取消</nut-button>
                    <nut-button type="primary" class="w-[200rpx]" size="small" @tap="confirmTimeSelection">确认</nut-button>
                </view>
            </view>
        </nut-popup>

        <nut-popup v-model:visible="showMap" position="bottom" :style="{ height: '80%' }">
            <view class="h-full">
                <map class="w-full h-[90%]" :latitude="latitude" :longitude="longitude" :markers="markers"
                    @tap="chooseLocation" />
                <view class="flex justify-between items-center p-4">
                    <text>{{ address }}</text>
                    <nut-button type="success" size="small" @tap="confirmLocation">确定</nut-button>
                    <!-- <button class="bg-green-500 text-white px-[20rpx] py-[10rpx] rounded text-sm" @tap="confirmLocation">确定</button> -->
                </view>
            </view>
        </nut-popup>

    </view>

</template>

<script lang="ts" setup>
import { defineComponent, onMounted, ref, watch, computed } from 'vue';
import { View, Text, Map } from '@tarojs/components';
import { DatePicker, Popup, Picker } from '@nutui/nutui-taro';
// import { Popup } from '@nutui/nutui-taro';
import { useNurseGoods } from '@/service';
// import { TENCENT_MAP_KEY } from '@/constants/service';
import Taro, { showToast } from '@tarojs/taro';
import { calculateDistance } from '@/utils';
import { storeToRefs } from 'pinia';
import { useAuthStore, useGoodsStore } from '@/store';
import { getLastTimeStr, getListTimeStr } from './tooler';
import DateView from './date-view.vue';
import { getFeeControl } from '@/service/api/nurse_orders';

const goodsStore = useGoodsStore();

// 直接使用 store 实例访问属性
const sku = computed(() => goodsStore.sku);
const night = computed(() => goodsStore.night);
const festival = computed(() => goodsStore.festival);
const urgent = computed(() => goodsStore.urgent);
const expert = computed(() => goodsStore.expert);
const distanceStore = computed(() => goodsStore.distance);
// const overtime = computed(() => goodsStore.overtime);
const distanceFee = computed(() => goodsStore.distanceFee);
const pickup = computed(() => goodsStore.pickup);
const pickupFree = computed(() => goodsStore.pickupFree);
const festivalFree = computed(() => goodsStore.festivalFree);
const expertFree = computed(() => goodsStore.expertFree);
// const beginDate = computed(() => goodsStore.beginDate);
// const endDate = computed(() => goodsStore.endDate);
const overtimeFee = computed(() => goodsStore.overtimeFee);
const feeControl = computed(() => goodsStore.feeControl);
const isAdd = ref('0');


const { nurseUser } = storeToRefs(useAuthStore());
const { loadDistance } = useNurseGoods();
const TENCENT_MAP_KEY = "5UQBZ-3CUKW-WRURZ-3I4LN-7N6WK-ZGF75"

const pickFieldNames = {
    text: 'name',
    value: 'fee'
}
const showTimePicker = ref(false);
const showTechPicker = ref(false);
const showMap = ref(false);
const val = ref(new Date());
const min = ref(new Date(2020, 1, 1));
const max = ref(new Date(2030, 12, 31));
// const startDate = ref<string | null>(null);
// const endDate = ref<string | null>(null);
const isFast = ref('0');
const fastNum = ref(0);
const pickNum = computed(() => {
    if (isPick.value === '1') {
        return totalWay.value;
    }
    return 0;
})
const totalWay = computed(() => {
    if (records.value.length === 0 || !distance.value) {
        return 0;
    }

    let t = 0;
    records.value.forEach((item: any) => {
        if (distance.value && distance.value >= item.beginKm) {
            t += item.fee;
        }
    });
    if (isWeek.value === '1' && records.value[0]) {
        return t + records.value[0].fee;
    }
    return t;
});

const getMinStartDate = () => {
    const now = new Date();
    // const hours = isFast.value === '1' ? 3 : 48;
    const hours = 3;
    return new Date(now.getTime() + hours * 60 * 60 * 1000);
};

// watch(isFast, () => {
//     min.value = getMinStartDate();
//     startDate.value = null;
//     endDate.value = null;
//     fastNum.value = 0;
// });

const latitude = ref(nurseUser.value?.latitude);
const longitude = ref(nurseUser.value?.longitude);
const address = ref(nurseUser.value?.areaName + nurseUser.value?.address);
const distance = ref(null);
const markers = ref([{
    id: 1,
    latitude: 22.817002,
    longitude: 108.366543,
    width: 30,
    height: 30
}]);

const openMap = () => {
    showMap.value = true;
};

const chooseLocation = (e: any) => {
    const { latitude: lat, longitude: lng } = e.detail;
    latitude.value = lat;
    longitude.value = lng;
    markers.value = [{
        id: 1,
        latitude: lat,
        longitude: lng,
        width: 30,
        height: 30
    }];
    // 根据坐标获取地址信息
    wx.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${TENCENT_MAP_KEY}`,
        success: (res: any) => {
            console.log('res', res);
            if (res.data.status === 0) {
                address.value = res.data.result.address;
                // 计算距离
                const distance = res.data.result.distance;
                if (distance) {
                    distance.value = (distance / 1000).toFixed(1);
                }
            } else {
                showToast({
                    title: '获取地址信息失败',
                    icon: 'error'
                });
            }
        },
        fail: (error: any) => {
            console.error('获取地址信息失败：', error);
            showToast({
                title: '获取地址信息失败',
                icon: 'error'
            });
        }
    });
};

const confirmLocation = () => {
    showMap.value = false;
    console.log('Selected location:', {
        latitude: latitude.value,
        longitude: longitude.value,
        address: address.value
    });

    getLocation();
};

// const isFast = ref('0');
const isMoon = ref('0');
const isPick = ref('0');
const isWeek = ref('0');
const isType = ref('0');

const techLevel = ref(0);
const techPickerValue = ref([0]);
// const techLevelOptions = [
//     { text: '0元', value: 0 },
//     { text: '200元', value: 200 },
//     { text: '400元', value: 400 },
//     { text: '600元', value: 600 },
// ];

const spePickerValue = ref([0])
const speLevelOptions = ref([])

const showHurry = ref(false);
const hurryValue = ref([0]);
// const hurryOptions = [
//     { text: '3-6小时入户加400(不含夜班)', value: 400 },
//     { text: '6-24小时入户加200(不含夜班)', value: 200 },
//     { text: '24-48小时入户加0(不含夜班)', value: 0 },
// ]

// 时间段费用提示相关
const showTimeAlert = ref(false);
const timeAlertInfo = ref({
    isNightShift: false,
    isWeekend: false,
    hurryFee: 0
});
const pendingTimeSelection = ref({
    type: '',
    value: '',
    selectedValue: null
});

const popTechPicker = () => {
    showTechPicker.value = true;
};

const showSpePicker = ref(false)      
const popSpePicker = () => {
    showSpePicker.value = true;
}

const confirmTechLevel = ({ selectedValue }: { selectedValue: any[] }) => {
    console.log('selectedValue level', selectedValue);
    techLevel.value = selectedValue[0];
    techPickerValue.value = selectedValue;
    showTechPicker.value = false;
    expert.value.cur = expert.value.options.find((item: any) => item.fee === selectedValue[0]) || {};
    console.log('expert.value 😂😂', expert.value);
};
const speLevel = ref("")
const confirmSpeLevel = ({ selectedValue }: { selectedValue: any[] }) => {
    console.log('selectedValue level', selectedValue);
    speLevel.value = selectedValue[0];
    spePickerValue.value = selectedValue;
    showSpePicker.value = false;
};

const confirmHurry = ({ selectedValue }: { selectedValue: any[] }) => {
    console.log('selectedValue hurry', selectedValue);
    // hurryValue.value = selectedValue;
    showHurry.value = false;
    urgent.value.cur = urgent.value.options.find((item: any) => item.fee === selectedValue[0]) || {};
}

const changeTechLevel = ({ selectedValue }: { selectedValue: any[] }) => {
    techPickerValue.value = selectedValue;
};

let popType = 'start'
const records = ref([]);

onMounted(() => {
    
    loadDistance().then((res) => {
        console.log('loadDistance', res);
        records.value = res.success?.records || [];
    });
    goodsStore.family = nurseUser.value?.nurseUserFamilyList?.[0] || {};
    // getLocation();
    // const obj = nurseUser.value.nurseUserAddrList?.[0];
    
    console.log('nurseUser.value.nurseUserHomeAddrList 0-------', nurseUser.value.nurseHomeAddrList);
    const obj = nurseUser.value.nurseHomeAddrList.find((item: any) => item.isDefault == true);
    console.log('obj 1-------', obj);
    if(!obj){
        Taro.showToast({
            title: '请先设置家庭地址',
            icon: 'none'
        });
        return
    }
    latitude.value = (obj as any)?.latitude;
    longitude.value = (obj as any)?.longitude;
    address.value = (obj?.areaName || '') + (obj?.address || '');
    nurseUser.value.defaultHospitalLatitude
    distance.value = calculateDistance(latitude.value, longitude.value, nurseUser.value.defaultHospitalLatitude, nurseUser.value.defaultHospitalLongitude, 1);
});

const calculateFastNum = (selectedDate: Date) => {
    if (isFast.value === '0') return 0;

    const now = new Date();
    const hoursDiff = (selectedDate.getTime() - now.getTime()) / (1000 * 60 * 60);
    console.log(`距离当前时间：${hoursDiff.toFixed(1)}小时`);
    // console.log(`计算得到的 fastNum：${calculateFastNum(selectedDate)}元`);


    if (hoursDiff <= 6) return 400;
    if (hoursDiff <= 48) return 200;
    return 0;
};

function getTimestr(list: any) {
    return `${list[0]}-${list[1]}-${list[2]} ${list[3]}:${list[4]}`
    // const now = new Date();
    // const hours = isFast.value === '1' ? 3 : 48;
    // return new Date(now.getTime() + hours * 60 * 60 * 1000);
}

// 根据时间段自动计算加急费用
const calculateHurryFee = (startTime: string) => {
    if (!startTime) return 0;
    
    const startDate = new Date(startTime);
    const now = new Date();
    const hoursDiff = (startDate.getTime() - now.getTime()) / (1000 * 60 * 60);
    
    console.log(`距离当前时间：${hoursDiff.toFixed(1)}小时`);
    
    if (hoursDiff <= 6) return 400;      // 3-6小时入户加400
    if (hoursDiff <= 24) return 200;     // 6-24小时入户加200
    if (hoursDiff <= 48) return 0;       // 24-48小时入户加0
    return 0; // 48小时以上不加急
};

// 检查时间段是否包含夜班时间和周末
const checkTimeRange = (startTime: string, endTime?: string) => {
    const result = {
        isNightShift: false,
        isWeekend: false,
        hurryFee: 0
    };

    if (!startTime) return result;

    const startDate = new Date(startTime);
    const endDate = endTime ? new Date(endTime) : new Date(startDate.getTime() + 8 * 60 * goodsStore.duration * 1000); // 默认8小时

    // 检查是否包含周末
    const startDay = startDate.getDay();
    const endDay = endDate.getDay();
    if (startDay === 0 || startDay === 6 || endDay === 0 || endDay === 6) {
        result.isWeekend = true;
    }

    // 检查是否包含夜班时间 (18:00 - 次日9:00)
    const checkNightShift = (date: Date) => {
        const hour = date.getHours();
        return hour >= 18 || hour < 9;
    };

    // 检查开始时间和结束时间是否在夜班时间范围内
    if (checkNightShift(startDate) || checkNightShift(endDate)) {
        result.isNightShift = true;
    }

    // 如果跨天，需要检查是否跨越了夜班时间
    if (endDate.getDate() !== startDate.getDate()) {
        result.isNightShift = true;
    }

    // 计算加急费用
    result.hurryFee = calculateHurryFee(startTime);

    return result;
};
const confirmTime = (value: any) => {
    console.log('value 😂😂', value);
    console.log('goodsStore.beginDate', goodsStore.beginDate);
    console.log('goodsStore.endDate', goodsStore.endDate);
    console.log('goodsStore data===', goodsStore);
   
    const list = value.selectedValue;
    const timeStr = getListTimeStr(list);
    if(popType === 'start'){
        goodsStore.beginDate = timeStr;
        goodsStore.endDate = getLastTimeStr(timeStr, goodsStore.duration / 60);
    }else{
        goodsStore.endDate = timeStr;
    }
    // const timeStr = getTimestr(value.selectedValue);
    const timeCheck = checkTimeRange(goodsStore.beginDate, goodsStore.endDate);
    console.log('timeCheck 😂😂', timeCheck);
    if(timeCheck.isNightShift){
        Taro.showToast({
            title: '请选择非夜班时间',
            icon: 'none'
        });
        goodsStore.beginDate = '';
        goodsStore.endDate = '';
        return;
    }
    showTimePicker.value = false;
    // fastNum.value = calculateFastNum(selectedDate);

   
    
    // 检查时间段费用
    // const currentStartTime = popType === 'start' ? timeStr : goodsStore.beginDate;
    // const currentEndTime = popType === 'end' ? timeStr : goodsStore.endDate;
    
    // const timeCheck = checkTimeRange(currentStartTime || '', currentEndTime || '');
    
    // if (timeCheck.isNightShift || timeCheck.isWeekend || timeCheck.hurryFee > 0) {
    //     // 保存待确认的时间选择
    //     pendingTimeSelection.value = {
    //         type: popType,
    //         value: timeStr,
    //         selectedValue: value.selectedValue
    //     };
        
    //     // 显示费用提示
    //     timeAlertInfo.value = timeCheck;
    //     showTimeAlert.value = true;
    //     return;
    // }
    
    // // 直接确认时间选择（没有额外费用时）
    // // 仍然需要设置加急费用（如果有的话）
    // if (timeCheck.hurryFee > 0) {
    //     hurryValue.value = [timeCheck.hurryFee];
    // }
    // confirmTimeDirectly(popType, timeStr);
};

// 直接确认时间选择（不弹出提示）
const confirmTimeDirectly = (type: string, timeStr: string) => {
    if (type === 'start') {
        startDate.value = timeStr;
    } else if (type === 'end') {
        endDate.value = timeStr;
    }
};

// 确认时间选择（带费用提示）
const confirmTimeSelection = () => {
    const { type, value } = pendingTimeSelection.value;
    
    // 自动设置夜班和节假日选项
    if (timeAlertInfo.value.isNightShift) {
        isMoon.value = '1';
    }
    if (timeAlertInfo.value.isWeekend) {
        isWeek.value = '1';
    }
    
    // 自动设置加急费用
    if (timeAlertInfo.value.hurryFee > 0) {
        hurryValue.value = [timeAlertInfo.value.hurryFee];
    }
    
    confirmTimeDirectly(type, value);
    showTimeAlert.value = false;
};

// 取消时间选择
const cancelTimeSelection = () => {
    showTimeAlert.value = false;
    pendingTimeSelection.value = {
        type: '',
        value: '',
        selectedValue: null
    };
};

// 获取当前加急费
const getCurrentHurryFee = () => {
    if (!startDate.value) return 0;
    return Array.isArray(hurryValue.value) ? hurryValue.value[0] : hurryValue.value;
};

// 获取时间段总费用
const getTotalTimeFee = () => {
    let total = 0;
    
    // 加急费
    total += getCurrentHurryFee();
    
    // 夜班费
    if (isMoon.value === '1') {
        total += 1000;
    }
    
    // 节假日费
    if (isWeek.value === '1') {
        total += 500;
    }
    
    return total;
};

const popPicker = (type: any) => {
    console.log('popPicker', type);
    popType = type;
    showTimePicker.value = true;
    min.value = getMinStartDate();
};
const togglePicker = () => {
    showTimePicker.value = !showTimePicker.value;
};

// 获取用户当前位置
function getLocation() {
    try {
        Taro.getLocation({
            type: 'wgs84',
            // type: 'gcj02',
            needFullAccuracy: true,
            success(res) {
                // latitude.value = res.latitude;
                // longitude.value = res.longitude;

                // 根据坐标获取地址信息
                distance.value = calculateDistance(res.latitude, res.longitude, latitude.value, longitude.value, 2)
                distanceStore.value.num = distance.value;

            }
        });
    } catch (err) {
        Taro.showModal({
            title: '提示',
            content: '获取位置服务信息失败!',
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    // console.log('用户点击确定')
                } else if (res.cancel) {
                    // console.log('用户点击取消')
                }
            }
        });
    }
}
defineExpose({
  getPrice() {
    const hurryPrice = Array.isArray(hurryValue.value) ? hurryValue.value[0] : hurryValue.value;
    return hurryPrice + techLevel.value + pickNum.value + fastNum.value;
  },
  getTimestr(){
    return {
        // beginDate: startDate.value,
        // endDate: endDate.value,
    }
  }
})
</script>


<style lang="scss">
.iptx{
    font-size: 24rpx !important;
    input{
        font-size: 24rpx !important;
       
    }
}
.nut-input{
    padding: 12rpx !important;
}
</style>
